package model

import (
	"chat.com/pkg/snowflake"
	"gorm.io/plugin/soft_delete"
)

const (
	MessageTypeText = "text"

	MessageCmdMsg   = "msg"
	MessageCmdEnter = "enter"
	MessageCmdExit  = "exit"
)

// 单聊消息发件箱
type SingleMessageSendBox struct {
	Id        int64                 `json:"id" gorm:"type:bigint; primaryKey"` // 主键自增id
	CreatedAt int64                 `json:"created_at" gorm:"type:bigint; not null; default CURRENT_TIMESTAMP"`
	UpdatedAt int64                 `json:"updated_at" gorm:"type:bigint; not null; default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP"`
	DeletedAt soft_delete.DeletedAt `json:"deleted_at" gorm:"type:bigint; not null; default 0"`

	AppId       int64  `json:"app_id"         gorm:"type:tinyint;     not null;  comment:'平台类型'"`
	Type        string `json:"type"           gorm:"type:varchar(15);     not null;  comment:'消息类型 text/img/'"`
	Content     string `json:"content"        gorm:"type:text;        not null;  comment:'消息内容'"`
	SenderId    int64  `json:"sender_id"      gorm:"type:bigint;      not null;  comment:'发送者'"`
	RecieverId  int64  `json:"reciever_id"    gorm:"type:bigint;      not null;  comment:'接收者'"`
	SentTime    int64  `json:"sent_time"      gorm:"type:bigint;      not null;  comment:'发送时间'"`
	HasRead     int64  `json:"has_read"       gorm:"type:tinyint(1);  not null;  default 0; comment:'是否已读 0(未读) 1(已读)'"`
	HasReadTime int64  `json:"has_read_time"  gorm:"type:bigint;      not null;  default 0; comment:'已读时间'"`
}

// 群聊消息发件箱
type GroupMessageSendBox struct {
	Id        int64                 `json:"id" gorm:"type:bigint; primaryKey"` // 主键自增id
	CreatedAt int64                 `json:"created_at" gorm:"type:bigint; not null; default CURRENT_TIMESTAMP"`
	UpdatedAt int64                 `json:"updated_at" gorm:"type:bigint; not null; default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP"`
	DeletedAt soft_delete.DeletedAt `json:"deleted_at" gorm:"type:bigint; not null; default 0"`

	AppId    int64  `json:"app_id"            gorm:"type:tinyint; not null;  comment:'平台类型'"`
	Type     int64  `json:"type"              gorm:"type:tinyint; not null;  comment:'消息类型 text/img/'"`
	GroupId  int64  `json:"group_id"          gorm:"type:bigint;  not null;  comment:'群id'"`
	SenderId int64  `json:"sender_id"         gorm:"type:bigint;  not null;  comment:'发送者'"`
	Content  string `json:"content"           gorm:"type:text;    not null;  comment:'消息内容'"`
	SentTime int64  `json:"sent_time"         gorm:"type:bigint;  not null;  comment:'发送时间'"`
}

// 群聊消息收件箱
type GroupMessageRecieveBox struct {
	Id        int64                 `json:"id" gorm:"type:bigint; primaryKey"` // 主键自增id
	CreatedAt int64                 `json:"created_at" gorm:"type:bigint; not null; default CURRENT_TIMESTAMP"`
	UpdatedAt int64                 `json:"updated_at" gorm:"type:bigint; not null; default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP"`
	DeletedAt soft_delete.DeletedAt `json:"deleted_at" gorm:"type:bigint; not null; default 0"`

	GroupMessageSendBoxId int64  `json:"group_message_send_box_id"   gorm:"type:bigint;      not null;  comment:'群聊消息id'"`
	AppId                 int64  `json:"app_id"                      gorm:"type:tinyint;     not null;  comment:'平台类型'"`
	Type                  int64  `json:"type"                        gorm:"type:tinyint;     not null;  comment:'消息类型 text/img/'"`
	GroupId               int64  `json:"group_id"                    gorm:"type:bigint;      not null;  comment:'群id'"`
	SenderId              int64  `json:"sender_id"                   gorm:"type:bigint;      not null;  comment:'发送者'"`
	RecieverId            int64  `json:"reciever_id"                 gorm:"type:bigint;      not null;  comment:'接收者'"`
	Content               string `json:"content"                     gorm:"type:text;        not null;  comment:'消息内容'"`
	SentTime              int64  `json:"sent_time"                   gorm:"type:bigint;      not null;  comment:'发送时间'"`
	RecieveTime           int64  `json:"recieve_time"                gorm:"type:bigint;      not null;  default 0; comment:'接收时间'"`
	HasRead               int64  `json:"has_read"                    gorm:"type:tinyint(1);  not null;  default 0; comment:'是否已读'"`
	HasReadTime           int64  `json:"has_read_time"               gorm:"type:bigint;      not null;  default 0; comment:'已读时间'"`
}

// 系统消息发件箱
type SysMessageSendBox struct {
	Id        int64                 `json:"id" gorm:"type:bigint; primaryKey"` // 主键自增id
	CreatedAt int64                 `json:"created_at" gorm:"type:bigint; not null; default CURRENT_TIMESTAMP"`
	UpdatedAt int64                 `json:"updated_at" gorm:"type:bigint; not null; default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP"`
	DeletedAt soft_delete.DeletedAt `json:"deleted_at" gorm:"type:bigint; not null; default 0"`

	AppId    int64  `json:"app_id"     gorm:"type:tinyint; not null;  comment:'平台类型'"`
	Type     int64  `json:"type"       gorm:"type:tinyint; not null;  comment:'消息类型 text/img/'"`
	Content  string `json:"content"    gorm:"type:text;    not null;  comment:'消息内容'"`
	SentTime int64  `json:"sent_time"  gorm:"type:bigint;  not null;  comment:'发送时间'"`
}

// 用户读取系统消息进度表
type SysMessageOffset struct {
	Id        int64                 `json:"id" gorm:"type:bigint; primaryKey"` // 主键自增id
	CreatedAt int64                 `json:"created_at" gorm:"type:bigint; not null; default CURRENT_TIMESTAMP"`
	UpdatedAt int64                 `json:"updated_at" gorm:"type:bigint; not null; default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP"`
	DeletedAt soft_delete.DeletedAt `json:"deleted_at" gorm:"type:bigint; not null; default 0"`

	UserId int64 `json:"user_id"     gorm:"type:bigint; not null;  uniqueIndex:idx_user_id; comment:'用户id'"`
	Offset int64 `json:"offset"      gorm:"type:bigint; not null;  default 0; comment:'消息偏移量, 即用户最后收到的系统消息id'"`
}

// 新建一条单聊消息
func NewSingleMessage(appId int64, msgType string, content string, senderId int64, recieverId int64, sentTime int64) (id int64, err error) {

	id = snowflake.Snowflaker.Generate().Int64()

	message := SingleMessageSendBox{
		Id:         id,
		AppId:      appId,
		Type:       msgType,
		Content:    content,
		SenderId:   senderId,
		RecieverId: recieverId,
		SentTime:   sentTime,
	}

	if err = db.Create(&message).Error; err != nil {
		return 0, err
	}

	return id, nil
}

// 判断单聊消息是否已读, 并且返回已读时间
func IsSingleMessageRead(singleMessageSendBoxId int64) (ok bool, readTime int64) {

	var singleMessageSendBox SingleMessageSendBox
	if err := db.Where("id = ?", singleMessageSendBoxId).Find(&singleMessageSendBox).Error; err != nil {
		return false, 0
	}

	if singleMessageSendBox.Id == 0 {
		return false, 0
	}

	if singleMessageSendBox.HasRead == 0 {
		return false, singleMessageSendBox.HasReadTime
	}

	return true, singleMessageSendBox.HasReadTime
}

// 获取历史单聊消息, 按发送时间倒序返回, limit限制返回数量, offset设定起始偏移量, 涉及深分页问题待优化 todo
func GetSingleMessage(SenderId, RecieverId int64, limit, offset int) (singleMessageSendBoxs []SingleMessageSendBox, err error) {

	if err := db.Order("sent_time desc").Limit(limit).Offset(offset).Where(
		"sender_id = ? and reciever_id = ?", SenderId, RecieverId).Or(
		"sender_id = ? and reciever_id = ?", RecieverId, SenderId).Find(&singleMessageSendBoxs).Error; err != nil {

		return nil, err
	}

	return
}

// 删除单聊消息
func DeleteSingleMessage(id int64) (ok bool, err error) {

	if err = db.Where("id = ?", id).Delete(&SingleMessageSendBox{}).Error; err != nil {
		return false, err
	}

	return true, nil
}

// 新建一个群消息到发件箱
func NewGroupMessageSend(appId int64, msgType int64, groupId int64, senderId int64, content string, sentTime int64) (id int64, err error) {

	id = snowflake.Snowflaker.Generate().Int64()

	message := GroupMessageSendBox{
		Id:       id,
		AppId:    appId,
		Type:     msgType,
		GroupId:  groupId,
		SenderId: senderId,
		Content:  content,
		SentTime: sentTime,
	}

	if err := db.Create(&message).Error; err != nil {
		return 0, err
	}

	return id, nil
}

// 新建一个群消息到收件箱
func NewGroupMessageRecieve(groupMessageSendBoxId, appId, msgType, groupId, senderId, recieverId, sentTime int64,
	content string) (id int64, err error) {

	id = snowflake.Snowflaker.Generate().Int64()

	message := GroupMessageRecieveBox{
		Id:                    id,
		GroupMessageSendBoxId: groupMessageSendBoxId,
		AppId:                 appId,
		Type:                  msgType,
		GroupId:               groupId,
		SenderId:              senderId,
		RecieverId:            recieverId,
		Content:               content,
		SentTime:              sentTime,
	}

	if err := db.Create(&message).Error; err != nil {
		return 0, err
	}

	return id, nil
}

// 新建一个系统消息到发件箱
func NewSysMessageSend(appId, msgType, sentTime int64, content string) (id int64, err error) {

	id = snowflake.Snowflaker.Generate().Int64()

	message := SysMessageSendBox{
		Id:       id,
		AppId:    appId,
		Type:     msgType,
		Content:  content,
		SentTime: sentTime,
	}

	if err := db.Create(&message).Error; err != nil {
		return 0, err
	}

	return id, nil
}

// 新建一个用户的系统消息偏移量
func NewSysNessageOffset(userId int64) (id int64, err error) {

	id = snowflake.Snowflaker.Generate().Int64()

	offset := SysMessageOffset{
		Id:     id,
		UserId: userId,
	}

	if err := db.Create(&offset).Error; err != nil {
		return 0, err
	}

	return id, nil
}

// 更新一个用户的系统消息偏移量
func UpdateSysNessageOffset(userId, offset int64) (ok bool, err error) {

	if err = db.Model(&SysMessageOffset{}).Where("user_id = ?", userId).Update("offset", offset).Error; err != nil {
		return false, err
	}

	return true, nil
}

/*
func getTextMsgData(cmd string, appId uint32, msgType, content string, senderId, recieverId, sentTime int64) string {
	textMsg := NewTextMsg(appId, msgType, content, senderId, recieverId, sentTime)
	head := NewResponse(cmd, common.OK, "Ok", textMsg)

	return head.String()
}

// 文本消息
func GetMsgData(cmd string, appId uint32, msgType, content string, senderId, recieverId, sentTime int64) string {

	return getTextMsgData(
		cmd, appId, msgType, content, senderId, recieverId, sentTime,
	)
}

// 文本消息
func GetTextMsgData(appId uint32, msgType, content string, senderId, recieverId, sentTime int64) string {

	return getTextMsgData(
		"msg", appId, msgType, content, senderId, recieverId, sentTime,
	)
}

// 用户进入消息
func GetTextMsgDataEnter(appId uint32, msgType, content string, senderId, recieverId, sentTime int64) string {

	return getTextMsgData(
		"enter", appId, msgType, content, senderId, recieverId, sentTime,
	)
}

// 用户退出消息
func GetTextMsgDataExit(appId uint32, msgType, content string, senderId, recieverId, sentTime int64) string {

	return getTextMsgData(
		"exit", appId, msgType, content, senderId, recieverId, sentTime,
	)
}
*/
